package com.bzy.blp.service.impl;

import com.bzy.blp.mapper.*;
import com.bzy.blp.model.*;
import com.bzy.blp.param.AddDrillingParam;
import com.bzy.blp.param.ShowPileDetailParam;
import com.bzy.blp.param.ShowPileParam;
import com.bzy.blp.service.BasePileManageService;
import com.bzy.blp.utils.ListUtils;
import com.bzy.blp.view.*;
import com.bzy.common.config.Environment;
import com.bzy.common.exception.SqlException;
import com.lowagie.text.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class BasePileManageServiceImpl implements BasePileManageService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BasePileManageServiceImpl.class);

    @Autowired
    private TPileMapper tPileMapper;

    @Autowired
    private TPileProjectMapper tPileProjectMapper;

    @Autowired
    private TPileRegionMapper tPileRegionMapper;

    @Autowired
    private TDrillingMapper tDrillingMapper;

    @Autowired
    private TDrillingImgMapper tDrillingImgMapper;

    @Autowired
    private TCoreImgMapper tCoreImgMapper;

    @Autowired
    private TDringRigImgMapper tDringRigImgMapper;

    @Autowired
    private TPileImgMapper tPileImgMapper;

    @Autowired
    private TReportFormImgMapper tReportFormImgMapper;

    @Autowired
    private CreatePileWordProcessor createPileWordProcessor;

    //创建和修改项目
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createAndUpdatePileProject(TPileProject tPileProject) {
        Timestamp time = new Timestamp(System.currentTimeMillis());
        tPileProject.setUpdateTime(time);
        if (tPileProject.getId() == null) {
            tPileProject.setCreateTime(time);
            int row = tPileProjectMapper.insertSelective(tPileProject);
            if (row < 1) {
                throw new SqlException("insert PileProject error");
            }
        } else {
            int row = tPileProjectMapper.updateByPrimaryKeySelective(tPileProject);
            if (row < 1) {
                throw new SqlException("update PileProject error");
            }
        }
        return Environment.SUCCESS;
    }

    //展示项目
    @Override
    public List<TPileProject> showPileProject() {
        return tPileProjectMapper.selectAll();
    }

    //创建和修改区域
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createAndUpdateRegion(TPileRegion tPileRegion) {
        Timestamp time = new Timestamp(System.currentTimeMillis());
        if (tPileRegion.getId() == null) {
            tPileRegion.setCreateTime(time);
            tPileRegion.setUpdateTime(time);
            int row = tPileRegionMapper.insertSelective(tPileRegion);
            if (row < 1) {
                throw new SqlException("insert Region error");
            }
        } else {
            tPileRegion.setUpdateTime(time);
            int row = tPileRegionMapper.updateByPrimaryKeySelective(tPileRegion);
            if (row < 1) {
                throw new SqlException("update Region error");
            }
        }
        return Environment.SUCCESS;
    }

    //展示区域
    @Override
    public List<TPileRegion> showRegion(Integer pileProjectId) {
        return tPileRegionMapper.selectAll(pileProjectId);
    }

    //创建和修改桩
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createAndUpdatePile(TPile tPile) {
        Timestamp time = new Timestamp(System.currentTimeMillis());
        tPile.setUpdateTime(time);
        if (null == tPile.getId()) {
            tPile.setCreateTime(time);
            int row = tPileMapper.insertSelective(tPile);
            if (row < 1) {
                throw new SqlException("insert tpile error");
            }
        } else {
            int row = tPileMapper.updateByPrimaryKeySelective(tPile);
            if (row < 1) {
                throw new SqlException("update tpile error");
            }
        }
        return Environment.SUCCESS;
    }

    //展示桩
    @Override
    public List<TPile> showPile(ShowPileParam showPileParam) {
        return tPileMapper.selectAll(showPileParam);
    }

    //创建和修改钻孔
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createAndUpdateDrilling(AddDrillingParam addDrillingParam) {
        Timestamp time = new Timestamp(System.currentTimeMillis());
        TDrilling tDrilling = new TDrilling();
        tDrilling.setId(addDrillingParam.getId());
        tDrilling.setPileId(addDrillingParam.getPileId());
        tDrilling.setDrillingNo(addDrillingParam.getDrillingNo());
        tDrilling.setaActualPileLength(addDrillingParam.getaActualPileLength());
        tDrilling.setBearingCoreLength(addDrillingParam.getBearingCoreLength());
        tDrilling.setConcreteLength(addDrillingParam.getConcreteLength());
        tDrilling.setDrillingDepthBearingStratum(addDrillingParam.getDrillingDepthBearingStratum());
        tDrilling.setEndHoleDepth(addDrillingParam.getEndHoleDepth());
        tDrilling.setPileConcreteYield(addDrillingParam.getPileConcreteYield());
        tDrilling.setSedimentThickness(addDrillingParam.getSedimentThickness());
        tDrilling.setUpdateTime(time);
        if (addDrillingParam.getId() == null) {
            tDrilling.setCreateTime(time);
            //添加钻孔信息
            int row = tDrillingMapper.insertDrilling(tDrilling);
            if (row < 1) {
                throw new SqlException("insert Region error");
            }
            //添加钻孔图片
            if (!ListUtils.isEmpty(addDrillingParam.getDrillingImgs())) {
                for (String img : addDrillingParam.getDrillingImgs()) {
                    TDrillingImg tDrillingImg = new TDrillingImg();
                    tDrillingImg.setDrillingId(tDrilling.getId());
                    tDrillingImg.setImg(img);
                    tDrillingImg.setCreateTime(time);
                    tDrillingImg.setUpdateTime(time);
                    row = tDrillingImgMapper.insertSelective(tDrillingImg);
                    if (row < 1) {
                        throw new SqlException("insert tDrillingImg error");
                    }
                }

            }
        } else {
            int row = tDrillingMapper.updateByPrimaryKeySelective(tDrilling);
            if (row < 1) {
                throw new SqlException("update tDrilling error");
            }
            //添加钻孔图片
            if (!ListUtils.isEmpty(addDrillingParam.getDrillingImgs())) {
                for (String img : addDrillingParam.getDrillingImgs()) {
                    TDrillingImg tDrillingImg = new TDrillingImg();
                    tDrillingImg.setDrillingId(addDrillingParam.getId());
                    tDrillingImg.setImg(img);
                    tDrillingImg.setCreateTime(time);
                    tDrillingImg.setUpdateTime(time);
                    row = tDrillingImgMapper.insertSelective(tDrillingImg);
                    if (row < 1) {
                        throw new SqlException("insert tDrillingImg error");
                    }
                }

            }
            //添加芯样图片
            if (!ListUtils.isEmpty(addDrillingParam.getCoreImgs())) {
                for (String img : addDrillingParam.getCoreImgs()) {
                    TCoreImg tCoreImg = new TCoreImg();
                    tCoreImg.setDrillingId(addDrillingParam.getId());
                    tCoreImg.setImg(img);
                    tCoreImg.setCreateTime(time);
                    tCoreImg.setUpdateTime(time);
                    row = tCoreImgMapper.insertSelective(tCoreImg);
                    if (row < 1) {
                        throw new SqlException("insert tCoreImg error");
                    }
                }

            }
            //添加报表图片
            if (!ListUtils.isEmpty(addDrillingParam.getReportFormImgs())) {
                for (String img : addDrillingParam.getReportFormImgs()) {
                    TReportFormImg tReportFormImg = new TReportFormImg();
                    tReportFormImg.setDrillingId(addDrillingParam.getId());
                    tReportFormImg.setImg(img);
                    tReportFormImg.setCreateTime(time);
                    tReportFormImg.setUpdateTime(time);
                    row = tReportFormImgMapper.insertSelective(tReportFormImg);
                    if (row < 1) {
                        throw new SqlException("insert tReportFormImg error");
                    }
                }

            }
            //添加钻机图片
            if (!ListUtils.isEmpty(addDrillingParam.getDrillingRigImgs())) {
                for (String img : addDrillingParam.getDrillingRigImgs()) {
                    TDringRigImg tDringRigImg = new TDringRigImg();
                    tDringRigImg.setDrillingId(addDrillingParam.getId());
                    tDringRigImg.setImg(img);
                    tDringRigImg.setCreateTime(time);
                    tDringRigImg.setUpdateTime(time);
                    row = tDringRigImgMapper.insertSelective(tDringRigImg);
                    if (row < 1) {
                        throw new SqlException("insert tDringRigImg error");
                    }
                }

            }
            //添加桩图片
            if (!ListUtils.isEmpty(addDrillingParam.getPileImgs())) {
                for (String img : addDrillingParam.getPileImgs()) {
                    TPileImg tPileImg = new TPileImg();
                    tPileImg.setDrillingId(addDrillingParam.getId());
                    tPileImg.setImg(img);
                    tPileImg.setCreateTime(time);
                    tPileImg.setUpdateTime(time);
                    row = tPileImgMapper.insertSelective(tPileImg);
                    if (row < 1) {
                        throw new SqlException("insert tPileImg error");
                    }
                }

            }
        }
        return Environment.SUCCESS;
    }

    //统计区域桩
    @Override
    public ShowPileDetailView showPileDetail(ShowPileDetailParam showPileDetailParam) {
        //先查出桩信息
        TPile tPile = tPileMapper.selectByPrimaryKey(showPileDetailParam.getPileId());
        if(null == tPile){
            return new ShowPileDetailView();
        }
        //在查出钻孔信息
        List<TDrilling> tDrillings = tDrillingMapper.getDrillingsByPileId(tPile.getId());
        List<DrillingDetailView> drillingDetailViews = new ArrayList<>();
        for (TDrilling tDrilling : tDrillings) {
            //查出钻孔对应的最后一次上传的芯样照片
            TCoreImg tCoreImg = tCoreImgMapper.getCoreImgByDrillingId(tDrilling.getId());
            DrillingDetailView drillingDetailView = new DrillingDetailView();
            drillingDetailView.setDrillingNo(tDrilling.getDrillingNo());
            drillingDetailView.setRigNo(tDrilling.getRigNo());
            drillingDetailView.setOpenDrillingTime(tDrilling.getOpenDrillingTime());
            drillingDetailView.setDrillingDepthBearingStratum(tDrilling.getDrillingDepthBearingStratum());
            drillingDetailView.setCreateTime(tDrilling.getCreateTime());
            drillingDetailView.setConcreteLength(tDrilling.getConcreteLength());
            drillingDetailView.setBearingCoreLength(tDrilling.getBearingCoreLength());
            drillingDetailView.setaActualPileLength(tDrilling.getaActualPileLength());
            if(null != tCoreImg){
                drillingDetailView.setCordImg(tCoreImg.getImg());
            }
            drillingDetailView.setEndHoleDepth(tDrilling.getEndHoleDepth());
            drillingDetailView.setPileId(tDrilling.getPileId());
            drillingDetailView.setId(tDrilling.getId());
            drillingDetailView.setPileConcreteYield(tDrilling.getPileConcreteYield());
            drillingDetailView.setSedimentThickness(tDrilling.getSedimentThickness());
            drillingDetailView.setUpdateTime(tDrilling.getUpdateTime());
            drillingDetailViews.add(drillingDetailView);
        }
        ShowPileDetailView showPileDetailView = new ShowPileDetailView();
        showPileDetailView.settDrillingDetails(drillingDetailViews);
        showPileDetailView.settPile(tPile);
        return showPileDetailView;
    }

    @Override
    public CensusPilesView censusPiles(Integer regionId) {
        //先查出该区域下的桩数量
        List<TPile> tPiles = tPileMapper.selectPileByRegionId(regionId);

        //设计等级
        pileIntegrityView pileIntegrityViewI = new pileIntegrityView();
        pileIntegrityViewI.setPileIntegrity((byte) 1);
        pileIntegrityViewI.setNum(0);
        List<String> pileNoI = new ArrayList<>();

        pileIntegrityView pileIntegrityViewII = new pileIntegrityView();
        pileIntegrityViewII.setPileIntegrity((byte) 2);
        pileIntegrityViewII.setNum(0);
        List<String> pileNoII = new ArrayList<>();

        pileIntegrityView pileIntegrityViewIII = new pileIntegrityView();
        pileIntegrityViewIII.setPileIntegrity((byte) 3);
        pileIntegrityViewIII.setNum(0);
        List<String> pileNoIII = new ArrayList<>();

        pileIntegrityView pileIntegrityViewIV = new pileIntegrityView();
        pileIntegrityViewIV.setPileIntegrity((byte) 4);
        pileIntegrityViewIV.setNum(0);
        List<String> pileNoIV = new ArrayList<>();


        //混凝土强度
        ConcreteDesignGradeView concreteDesignGradeView1 = new ConcreteDesignGradeView();
        concreteDesignGradeView1.setConcreteDesignGrade((byte) 1);
        concreteDesignGradeView1.setNum(0);
        List<String> concretePileNo1 = new ArrayList<>();

        ConcreteDesignGradeView concreteDesignGradeView2 = new ConcreteDesignGradeView();
        concreteDesignGradeView2.setConcreteDesignGrade((byte) 2);
        concreteDesignGradeView2.setNum(0);
        List<String> concretePileNo2 = new ArrayList<>();


        //沉渣厚度
        SedimentThicknessView sedimentThicknessView1 = new SedimentThicknessView();
        sedimentThicknessView1.setSedimentThickness((byte) 1);
        sedimentThicknessView1.setNum(0);
        List<String> sedimentPileNo1 = new ArrayList<>();

        SedimentThicknessView sedimentThicknessView2 = new SedimentThicknessView();
        sedimentThicknessView2.setSedimentThickness((byte) 2);
        sedimentThicknessView2.setNum(0);
        List<String> sedimentPileNo2 = new ArrayList<>();


        //持力层
        BearingLayerView bearingLayerView1 = new BearingLayerView();
        bearingLayerView1.setBearingLayer((byte) 1);
        bearingLayerView1.setNum(0);
        List<String> bearingPileNo1 = new ArrayList<>();

        BearingLayerView bearingLayerView2 = new BearingLayerView();
        bearingLayerView2.setBearingLayer((byte) 2);
        bearingLayerView2.setNum(0);
        List<String> bearingPileNo2 = new ArrayList<>();


        //桩整体状态
        PileStatusView pileStatusView1 = new PileStatusView();
        pileStatusView1.setPileStatus((byte) 1);
        pileStatusView1.setNum(0);
        List<String> pileNo1 = new ArrayList<>();

        PileStatusView pileStatusView2 = new PileStatusView();
        pileStatusView2.setPileStatus((byte) 1);
        pileStatusView2.setNum(0);
        List<String> pileNo2 = new ArrayList<>();

        //对该区域下的桩号进行分类
        tPiles.stream().forEach(tPile -> {
            //设计等级统计
            if (tPile.getpPileIntegrity() == 1) {
                pileIntegrityViewI.setNum(pileIntegrityViewI.getNum() + 1);
                pileNoI.add(tPile.getPileNumber());
            } else if (tPile.getpPileIntegrity() == 2) {
                pileIntegrityViewII.setNum(pileIntegrityViewII.getNum() + 1);
                pileNoII.add(tPile.getPileNumber());
            } else if (tPile.getpPileIntegrity() == 3) {
                pileIntegrityViewIII.setNum(pileIntegrityViewIII.getNum() + 1);
                pileNoIII.add(tPile.getPileNumber());
            } else if (tPile.getpPileIntegrity() == 4) {
                pileIntegrityViewIV.setNum(pileIntegrityViewIV.getNum() + 1);
                pileNoIV.add(tPile.getPileNumber());
            }

            boolean concreteFlag = false;
            switch (tPile.getConcreteDesignGrade()) {
                case 0:
                    if (tPile.getConcreteStrength().compareTo(BigDecimal.valueOf(20)) == -1) {
                        concreteFlag = true;
                    }
                    break;
                case 1:
                    if (tPile.getConcreteStrength().compareTo(BigDecimal.valueOf(30)) == -1) {
                        concreteFlag = true;
                    }
                    break;
                case 2:
                    if (tPile.getConcreteStrength().compareTo(BigDecimal.valueOf(40)) == -1) {
                        concreteFlag = true;
                    }
                    break;
                case 3:
                    if (tPile.getConcreteStrength().compareTo(BigDecimal.valueOf(50)) == -1) {
                        concreteFlag = true;
                    }
                    break;
                case 4:
                    if (tPile.getConcreteStrength().compareTo(BigDecimal.valueOf(60)) == -1) {
                        concreteFlag = true;
                    }
                    break;
                case 5:
                    if (tPile.getConcreteStrength().compareTo(BigDecimal.valueOf(70)) == -1) {
                        concreteFlag = true;
                    }
                    break;
                case 6:
                    if (tPile.getConcreteStrength().compareTo(BigDecimal.valueOf(80)) == -1) {
                        concreteFlag = true;
                    }
                    break;
            }
            //混凝土强度统计
            if (!concreteFlag) {
                concreteDesignGradeView1.setNum(concreteDesignGradeView1.getNum() + 1);
                concretePileNo1.add(tPile.getPileNumber());
            } else {
                concreteDesignGradeView2.setNum(concreteDesignGradeView2.getNum() + 1);
                concretePileNo2.add(tPile.getPileNumber());
            }

            //沉渣厚度统计
            if (tPile.getSedimentThicknessStatus() == 1) {
                sedimentThicknessView1.setNum(sedimentThicknessView1.getNum() + 1);
                sedimentPileNo1.add(tPile.getPileNumber());
            } else if (tPile.getSedimentThicknessStatus() == 2) {
                sedimentThicknessView2.setNum(sedimentThicknessView2.getNum() + 1);
                sedimentPileNo2.add(tPile.getPileNumber());
            }

            //持力层统计
            if (tPile.getBearingLayerStatus() == 1) {
                bearingLayerView1.setNum(bearingLayerView1.getNum() + 1);
                bearingPileNo1.add(tPile.getPileNumber());
            } else if (tPile.getBearingLayerStatus() == 2) {
                bearingLayerView2.setNum(bearingLayerView2.getNum() + 1);
                bearingPileNo2.add(tPile.getPileNumber());
            }

            //桩整体状态统计
            if (tPile.getStatus() == 1) {
                pileStatusView1.setNum(pileStatusView1.getNum() + 1);
                pileNo1.add(tPile.getPileNumber());
            } else if (tPile.getStatus() == 2) {
                pileStatusView2.setNum(pileStatusView2.getNum() + 1);
                pileNo2.add(tPile.getPileNumber());
            }
        });
        List<pileIntegrityView> pileIntegrityViews = new ArrayList<>();
        pileIntegrityViewI.setPileNo(pileNoI);
        pileIntegrityViews.add(pileIntegrityViewI);

        pileIntegrityViewII.setPileNo(pileNoII);
        pileIntegrityViews.add(pileIntegrityViewII);

        pileIntegrityViewIII.setPileNo(pileNoIII);
        pileIntegrityViews.add(pileIntegrityViewIII);

        pileIntegrityViewIV.setPileNo(pileNoIV);
        pileIntegrityViews.add(pileIntegrityViewIV);

        List<ConcreteDesignGradeView> ConcreteDesignGradeViews = new ArrayList<>();
        concreteDesignGradeView1.setPileNo(concretePileNo1);
        ConcreteDesignGradeViews.add(concreteDesignGradeView1);

        concreteDesignGradeView2.setPileNo(concretePileNo2);
        ConcreteDesignGradeViews.add(concreteDesignGradeView2);

        List<SedimentThicknessView> SedimentThicknessViews = new ArrayList<>();
        sedimentThicknessView1.setPileNo(sedimentPileNo1);
        SedimentThicknessViews.add(sedimentThicknessView1);

        sedimentThicknessView2.setPileNo(sedimentPileNo2);
        SedimentThicknessViews.add(sedimentThicknessView2);

        List<BearingLayerView> BearingLayerViews = new ArrayList<>();
        bearingLayerView1.setPileNo(bearingPileNo1);
        BearingLayerViews.add(bearingLayerView1);

        bearingLayerView1.setPileNo(bearingPileNo2);
        BearingLayerViews.add(bearingLayerView2);

        List<PileStatusView> PileStatusViews = new ArrayList<>();
        pileStatusView1.setPileNo(pileNo1);
        PileStatusViews.add(pileStatusView1);

        pileStatusView2.setPileNo(pileNo2);
        PileStatusViews.add(pileStatusView2);

        CensusPilesView censusPilesView = new CensusPilesView();
        censusPilesView.setPileIntegrityViews(pileIntegrityViews);
        censusPilesView.setBearingLayerViews(BearingLayerViews);
        censusPilesView.setConcreteDesignGradeViews(ConcreteDesignGradeViews);
        censusPilesView.setSedimentThicknessViews(SedimentThicknessViews);
        censusPilesView.setPileStatusViews(PileStatusViews);

        return censusPilesView;
    }

    @Override
    public List<String> createPileWord(List<ShowPileDetailParam> showPileDetailParams) {
        List<ShowPileDetailView> showPileDetailViews = new ArrayList<>();
        for (ShowPileDetailParam showPileDetailParam : showPileDetailParams) {
            ShowPileDetailView showPileDetailView = showPileDetail(showPileDetailParam);
            showPileDetailViews.add(showPileDetailView);
        }
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sdf.format(timestamp);
        List<String> wordList = new ArrayList<>();
        showPileDetailViews.stream().forEach(showPileDetailView -> {
            String path = "C:\\Users\\zhoubin\\Desktop\\芯样报表" + showPileDetailView.gettPile().getId() + "_" + time + ".doc";
            try {
                createPileWordProcessor.createPileWord(path, showPileDetailView);
            } catch (IOException e) {
                LOGGER.error(e.getCause().getMessage());
            } catch (DocumentException e) {
                LOGGER.error(e.getCause().getMessage());
            }
            wordList.add(path);
        });
        return wordList;
    }


}
